import 'package:flutter/material.dart';
import 'package:flutter_app/components/layout.dart';
import 'dart:math';

class Expansion extends StatefulWidget {
  final int durationMs;
  final double rad;
  final Curve curve;
  final bool clockwise;
  final Widget child;
  final String title;
  final TextStyle titleStyle;
  final bool active;

  Expansion(
      {this.durationMs = 200,
      this.rad = pi / 2,
      this.child,
      this.title,
      this.curve = Curves.fastOutSlowIn,
      this.clockwise = true,
      this.titleStyle,
      this.active});

  @override
  _ExpansionState createState() => _ExpansionState();
}

class _ExpansionState extends State<Expansion>
    with SingleTickerProviderStateMixin {
  double _rad = 0;
  bool _rotated;
  Animation _rotate;
  AnimationController _controller;

  @override
  void initState() {
    _rotated =widget.active ?? false;
    _controller = AnimationController(
        duration: Duration(milliseconds: widget.durationMs), vsync: this)
      ..addListener(() => setState(() =>
          _rad = (_rotated ? (1 - _rotate.value) : _rotate.value) * widget.rad))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _rotated = !_rotated;
        }
      });
    _rotate = CurvedAnimation(parent: _controller, curve: widget.curve);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        InkWell(
          onTap: () {
            _controller.reset();
            _controller.forward();
          },
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 10.0),
            child: RowBetween(children: [
              Text(
                widget.title,
                style: widget.titleStyle ??
                    TextStyle(
                        color: Colors.black,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
              ),
              Transform(
                  transform: Matrix4.rotationZ(widget.clockwise ? _rad : -_rad),
                  alignment: Alignment.center,
                  child: GestureDetector(
                      child: Icon(
                    Icons.arrow_forward_ios_outlined,
                    size: 14,
                  )))
            ]),
          ),
        ),
        Offstage(
          offstage: !_rotated,
          child: Row(
            children: [
              Container(
                  padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
                  child: widget.child),
            ],
          ),
        )
      ],
    );
  }
}
